package com.jielihaofeng.chat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jielihaofeng.chat.vo.ChatGroupVO;
import lombok.AllArgsConstructor;
import com.jielihaofeng.chat.convert.ChatGroupConvert;
import com.jielihaofeng.chat.dao.ChatGroupDao;
import com.jielihaofeng.chat.dao.ChatGroupUserDao;
import com.jielihaofeng.chat.entity.ChatGroupEntity;
import com.jielihaofeng.chat.entity.ChatGroupUserEntity;
import com.jielihaofeng.chat.query.ChatGroupQuery;
import com.jielihaofeng.chat.service.ChatGroupService;
import com.jielihaofeng.framework.common.page.PageResult;
import com.jielihaofeng.framework.common.service.impl.BaseServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 群组表
 *
 * @author 借力好风 949394048@qq.com
 * @since 1.0.0 2022-07-22
 */
@Service
@AllArgsConstructor
public class ChatGroupServiceImpl extends BaseServiceImpl<ChatGroupDao, ChatGroupEntity> implements ChatGroupService {

    private ChatGroupUserDao chatGroupUserDao;

    @Override
    public PageResult<ChatGroupVO> page(ChatGroupQuery query) {
        IPage<ChatGroupEntity> page = baseMapper.selectPage(getPage(query), getWrapper(query));

        return new PageResult<>(ChatGroupConvert.INSTANCE.convertList(page.getRecords()), page.getTotal());
    }

    private QueryWrapper<ChatGroupEntity> getWrapper(ChatGroupQuery query) {
        QueryWrapper<ChatGroupEntity> wrapper = new QueryWrapper<>();

        return wrapper;
    }

    @Override
    public void save(ChatGroupVO vo) {
        ChatGroupEntity entity = ChatGroupConvert.INSTANCE.convert(vo);

        baseMapper.insert(entity);

        // 保存群组人员信息
        List<Long> userIdList = vo.getUserIdList();
        userIdList.forEach(userId ->
                chatGroupUserDao.insert(
                        new ChatGroupUserEntity().setGroupId(vo.getId()).setUserId(userId))
        );

    }

    @Override
    public void update(ChatGroupVO vo) {
        ChatGroupEntity entity = ChatGroupConvert.INSTANCE.convert(vo);

        updateById(entity);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        removeById(id);

        // 删除群组人员信息
        chatGroupUserDao.delete(new LambdaQueryWrapper<ChatGroupUserEntity>().eq(ChatGroupUserEntity::getGroupId, id));
    }


}